// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package header

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/runtime"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"net/http"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
)

// Logic
// 钓场头部逻辑.
type Logic struct {
	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: NewResponse(),
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) error {
	return validator.Query(i, o.request)
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	for _, fn := range []func(context.Context) error{
		o.RunArcade,
		o.RunSwiper,
	} {
		if err = fn(ctx); err != nil {
			return res.WithError(err)
		}
	}
	return res.With(o.response)
}

// RunArcade
// 钓场信息.
func (o *Logic) RunArcade(ctx context.Context) (err error) {
	var (
		arcade *models.Arcades
		has    bool
	)

	// 1. 读取钓场.
	if arcade, has, err = services.NewArcadesService().Dao.GetById(ctx, o.request.ArcadeId); err != nil {
		return errs.ErrDatabaseQuery
	}

	// 2. 钓场不存在.
	if !has {
		return errs.ErrArcadeNotFound
	}

	// 3. 状态错误.
	if !arcade.State.IsEnabled() {
		return runtime.NewError(http.StatusBadGateway, arcade.State.Text())
	}

	// 4. 有效钓场.
	o.response.Arcade.With(arcade)
	return
}

// RunSwiper
// 钓场轮播图.
func (o *Logic) RunSwiper(ctx context.Context) (err error) {
	var (
		list []*models.ArcadeSwiper
		sess *db.Session
	)

	// 1. 建立连接.
	if sess, err = db.Config.GetSlave(ctx); err != nil {
		return errs.ErrDatabaseQuery
	}

	// 2. 查询数据.
	if err = sess.Where(
		"arcade_id = ? AND enabled = ?",
		o.request.ArcadeId,
		kind.EnabledYes,
	).OrderBy("sort asc").Find(&list, models.ArcadeSwiper{}); err != nil {
		return errs.ErrDatabaseQuery
	}

	// 3. 处理数据.
	for _, item := range list {
		o.response.AddSwiper(item)
	}
	return
}
